<template>
  <el-dialog
    v-model="visible"
    :title="isEdit ? '编辑部门' : '新增部门'"
    width="900px"
    :close-on-click-modal="false"
    top="5vh"
    @closed="handleClosed"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      class="department-form"
    >
      <!-- 基本信息 -->
      <el-divider content-position="left">基本信息</el-divider>

      <el-form-item label="部门名称" prop="department_name">
        <el-input
          v-model="formData.department_name"
          placeholder="请输入部门名称（必填，唯一）"
          maxlength="100"
          show-word-limit
        />
        <div class="form-hint">💡 部门名称必须唯一，不能与其他部门重复</div>
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="部门代码" prop="department_code">
            <el-input
              v-model="formData.department_code"
              placeholder="请输入部门代码（可选，不填自动生成）"
              maxlength="50"
            />
            <div class="form-hint">💡 不填写将自动生成唯一代码</div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="formData.status"
              placeholder="请选择状态"
              style="width: 100%"
            >
              <el-option label="活跃" value="active" />
              <el-option label="非活跃" value="inactive" />
              <el-option label="已归档" value="archived" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="部门描述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="3"
          placeholder="请输入部门描述（可选）"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <!-- 主责任人信息 -->
      <el-divider content-position="left">主责任人信息</el-divider>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="责任人姓名" prop="responsible_person">
            <el-select
              v-model="formData.responsible_person"
              filterable
              placeholder="请选择或输入责任人姓名（可选）"
              clearable
              style="width: 100%"
              @change="handleResponsiblePersonChange"
            >
              <el-option
                v-for="person in responsiblePersonOptions"
                :key="person.name"
                :label="person.name"
                :value="person.name"
              >
                <div class="person-option">
                  <div class="person-name">{{ person.name }}</div>
                  <div class="person-detail">
                    {{ person.email || "" }}
                    <span v-if="person.phone"> / {{ person.phone }}</span>
                  </div>
                </div>
              </el-option>
            </el-select>
            <div class="form-hint">
              💡 选择责任人后会自动填充邮箱、电话、职务信息
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="责任人职务" prop="responsible_title">
            <el-input
              v-model="formData.responsible_title"
              placeholder="请输入责任人职务（可选）"
              maxlength="50"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="责任人邮箱" prop="responsible_email">
            <el-input
              v-model="formData.responsible_email"
              placeholder="请输入责任人邮箱（可选）"
              maxlength="100"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="责任人电话" prop="responsible_phone">
            <el-input
              v-model="formData.responsible_phone"
              placeholder="请输入责任人电话（可选）"
              maxlength="20"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 备用责任人信息 -->
      <el-divider content-position="left">备用责任人信息（可选）</el-divider>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="备用责任人" prop="backup_person">
            <el-select
              v-model="formData.backup_person"
              filterable
              placeholder="请选择或输入备用责任人姓名（可选）"
              clearable
              style="width: 100%"
              @change="handleBackupPersonChange"
            >
              <el-option
                v-for="person in responsiblePersonOptions"
                :key="person.name"
                :label="person.name"
                :value="person.name"
              >
                <div class="person-option">
                  <div class="person-name">{{ person.name }}</div>
                  <div class="person-detail">
                    {{ person.email || "" }}
                    <span v-if="person.phone"> / {{ person.phone }}</span>
                  </div>
                </div>
              </el-option>
            </el-select>
            <div class="form-hint">
              💡 选择备用责任人后会自动填充邮箱、电话信息
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备用责任人邮箱" prop="backup_email">
            <el-input
              v-model="formData.backup_email"
              placeholder="请输入备用责任人邮箱（可选）"
              maxlength="100"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="备用责任人电话" prop="backup_phone">
        <el-input
          v-model="formData.backup_phone"
          placeholder="请输入备用责任人电话（可选）"
          maxlength="20"
          style="width: 50%"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSave" :loading="saving">
        保存
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from "vue";
import { ElMessage, ElForm } from "element-plus";
import type { FormRules } from "element-plus";

// 定义props
const props = defineProps({
  modelValue: { type: Boolean, default: false },
  departmentDetail: {
    type: Object,
    default: () => null,
  },
  isEdit: { type: Boolean, default: false },
  responsiblePersonOptions: {
    type: Array as () => Array<{
      name: string;
      email?: string;
      phone?: string;
      title?: string;
    }>,
    default: () => [],
  },
});

// 定义emits
const emit = defineEmits<{
  (e: "update:modelValue", value: boolean): void;
  (e: "save", data: any): void;
}>();

// visible computed 属性
const visible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => emit("update:modelValue", value),
});

// 表单引用
const formRef = ref<InstanceType<typeof ElForm>>();
const saving = ref(false);

// 责任人选项（从props获取，使用computed）
const responsiblePersonOptions = computed(() => props.responsiblePersonOptions);

// 表单数据
const formData = reactive({
  department_name: "",
  department_code: "",
  description: "",
  responsible_person: "",
  responsible_email: "",
  responsible_phone: "",
  responsible_title: "",
  backup_person: "",
  backup_email: "",
  backup_phone: "",
  status: "active" as "active" | "inactive" | "archived",
});

// 表单验证规则
const formRules: FormRules = {
  department_name: [
    { required: true, message: "请输入部门名称", trigger: "blur" },
    {
      min: 1,
      max: 100,
      message: "部门名称长度应在1-100个字符之间",
      trigger: "blur",
    },
  ],
  department_code: [
    { max: 50, message: "部门代码长度不能超过50个字符", trigger: "blur" },
  ],
  responsible_email: [
    {
      type: "email",
      message: "请输入正确的邮箱地址",
      trigger: "blur",
    },
  ],
  backup_email: [
    {
      type: "email",
      message: "请输入正确的邮箱地址",
      trigger: "blur",
    },
  ],
  status: [
    {
      validator: (rule, value, callback) => {
        if (value && !["active", "inactive", "archived"].includes(value)) {
          callback(new Error("状态只能是 active/inactive/archived"));
        } else {
          callback();
        }
      },
      trigger: "change",
    },
  ],
};

// 监听弹窗打开，初始化表单数据
watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      if (props.isEdit && props.departmentDetail) {
        // 编辑模式：填充表单
        const detail = props.departmentDetail;
        formData.department_name = detail.department_name || "";
        formData.department_code = detail.department_code || "";
        formData.description = detail.description || "";
        formData.responsible_person = detail.responsible_person || "";
        formData.responsible_email = detail.responsible_email || "";
        formData.responsible_phone = detail.responsible_phone || "";
        formData.responsible_title = detail.responsible_title || "";
        formData.backup_person = detail.backup_person || "";
        formData.backup_email = detail.backup_email || "";
        formData.backup_phone = detail.backup_phone || "";
        formData.status = detail.status || "active";
      } else {
        // 新增模式：重置表单
        resetForm();
      }
    }
  }
);

// 重置表单
const resetForm = () => {
  formData.department_name = "";
  formData.department_code = "";
  formData.description = "";
  formData.responsible_person = "";
  formData.responsible_email = "";
  formData.responsible_phone = "";
  formData.responsible_title = "";
  formData.backup_person = "";
  formData.backup_email = "";
  formData.backup_phone = "";
  formData.status = "active";
  formRef.value?.clearValidate();
};

// 处理主责任人选择变化
const handleResponsiblePersonChange = (value: string) => {
  if (value) {
    const person = props.responsiblePersonOptions.find((p) => p.name === value);
    if (person) {
      // 自动填充邮箱、电话、职务（如果有的话）
      if (person.email) {
        formData.responsible_email = person.email;
      }
      if (person.phone) {
        formData.responsible_phone = person.phone;
      }
      if (person.title) {
        formData.responsible_title = person.title;
      }
    } else {
      // 如果在下拉列表中找不到，可能是手动输入的，不清空已填写的内容
      console.log(`未找到责任人: ${value}，可能是手动输入`);
    }
  }
};

// 处理备用责任人选择变化
const handleBackupPersonChange = (value: string) => {
  if (value) {
    const person = props.responsiblePersonOptions.find((p) => p.name === value);
    if (person) {
      // 自动填充邮箱、电话（如果有的话）
      if (person.email) {
        formData.backup_email = person.email;
      }
      if (person.phone) {
        formData.backup_phone = person.phone;
      }
    }
  }
};

// 弹窗关闭时重置表单
const handleClosed = () => {
  resetForm();
};

// 取消
const handleCancel = () => {
  emit("update:modelValue", false);
};

// 保存
const handleSave = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    saving.value = true;

    // 构建提交数据
    const submitData: any = {
      department_name: formData.department_name,
      status: formData.status,
    };

    // 可选字段
    if (formData.department_code) {
      submitData.department_code = formData.department_code;
    }
    if (formData.description) {
      submitData.description = formData.description;
    }
    if (formData.responsible_person) {
      submitData.responsible_person = formData.responsible_person;
    }
    if (formData.responsible_email) {
      submitData.responsible_email = formData.responsible_email;
    }
    if (formData.responsible_phone) {
      submitData.responsible_phone = formData.responsible_phone;
    }
    if (formData.responsible_title) {
      submitData.responsible_title = formData.responsible_title;
    }
    if (formData.backup_person) {
      submitData.backup_person = formData.backup_person;
    }
    if (formData.backup_email) {
      submitData.backup_email = formData.backup_email;
    }
    if (formData.backup_phone) {
      submitData.backup_phone = formData.backup_phone;
    }

    emit("save", submitData);
  } catch (error) {
    console.error("表单验证失败:", error);
  } finally {
    saving.value = false;
  }
};
</script>

<style scoped lang="scss">
.department-form {
  max-height: 70vh;
  overflow-y: auto;
  padding-right: 10px;

  .form-hint {
    font-size: 12px;
    color: #909399;
    margin-top: 4px;
    line-height: 1.5;
  }

  :deep(.el-divider__text) {
    font-size: 14px;
    font-weight: 500;
    color: #303133;
  }

  .person-option {
    .person-name {
      font-weight: 500;
      color: #303133;
    }

    .person-detail {
      font-size: 12px;
      color: #909399;
      margin-top: 2px;
    }
  }
}
</style>
